//
//  XQOrderDetailPublicController.swift
//  Spark Peso
//
//  Created by 小琦 on 2025/2/6.
//

import UIKit
import Photos

class XQOrderDetailPublicController: XQBaseController,UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    
    var dataSource : XQOrderDetailPublishModel?
    
    var selectName : String? = ""
    var selectNumber : String? = ""
    var selectBirthday : String? = ""
    var identityType : String = ""
    
    private lazy var bgImageView : UIImageView = {
        let imageView = UIImageView()
        imageView.image = UIImage(named: "detail_publish_bg")
        imageView.isUserInteractionEnabled = true
        return imageView
    }()
    
    private lazy var contentView : UIView = {
        let view = UIView()
        view.frame = CGRect(x: 15, y:UIDevice.xq_statusHeight() + 73, width: UIDevice.xq_width() - 30, height: UIDevice.xq_height() - UIDevice.xq_statusHeight() - 73)
        view.setRoundCorners([.topLeft,.topRight], radius: 16)
        view.backgroundColor = .white
        return view
    }()
    
    private lazy var identityView : XQOrderPublicView = {
        let view = XQOrderPublicView()
        view.placeHolderName = "publish_identity"
        view.onTapHandle = {[weak self] in
            guard let srongify = self else {return}
            srongify.clickIdentity()
        }
        return view
    }()
    
    private lazy var lineView : UIView = {
        let view = UIView()
        view.backgroundColor = UIColor(hex: "#EFEFEF")
        view.isHidden = true
        return view
    }()
    
    private lazy var faceView : XQOrderPublicView = {
        let view = XQOrderPublicView()
        view.placeHolderName = "publish_face"
        view.onTapHandle = {[weak self] in
            guard let srongify = self else {return}
            srongify.clickFace()
        }
        return view
    }()
    
    private lazy var netBtn : UIButton = {
        let btn = UIButton(type: .custom)
        btn.setTitle("Next", for: .normal)
        btn.titleLabel?.font = UIFont.systemFont(ofSize: 20, weight: .medium)
        btn.setTitleColor(.white, for: .normal)
        btn.backgroundColor = .mainTextColor
        btn.layer.cornerRadius = 30
        btn.addTarget(self, action: #selector(nextClick), for: .touchUpInside)
        return btn
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        makeUI()
        makeConstraints()
        
        refreshData()
    }
    
    private func refreshData() {
        XQHud.showLoading(controller: self)
        
        let params : [String : String] = ["taxes":self.orderId]
        
        XQNetworkManager.shared.postRequest(url: "/figures/decreasing", parameters: params) {[weak self] response, error in
            guard let srongify = self else {return}
            XQHud.hideLoading(controller: srongify)
            
            if (response?.object == 0) {
                if let procedureModel = XQOrderDetailPublishModel.deserialize(from: response?.procedure) {
                    srongify.dataSource = procedureModel
                    srongify.updateTopInfo()
                }
            }
        }
    }
    
    private func makeUI() {
        self.view.insertSubview(self.bgImageView, belowSubview: self.navigationBar)
        self.bgImageView.addSubview(self.contentView)
        self.contentView.addSubview(self.identityView)
        self.contentView.addSubview(self.lineView)
        self.contentView.addSubview(self.faceView)
        self.contentView.addSubview(self.netBtn)
    }
    
    private func makeConstraints() {
        self.bgImageView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        self.contentView.snp.makeConstraints { make in
            make.top.equalTo(UIDevice.xq_statusHeight() + 73)
            make.left.equalTo(15)
            make.right.equalTo(-15)
            make.bottom.equalTo(0)
        }
        self.identityView.snp.makeConstraints { make in
            make.top.equalTo(30)
            make.left.equalTo(24)
            make.right.equalTo(-24)
            make.height.equalTo(74)
        }
        self.lineView.snp.makeConstraints { make in
            make.top.equalTo(self.identityView.snp.bottom).offset(37)
            make.left.equalTo(24)
            make.right.equalTo(-24)
            make.height.equalTo(1)
        }
        self.faceView.snp.makeConstraints { make in
            make.top.equalTo(self.lineView.snp.bottom).offset(37)
            make.left.equalTo(self.identityView.snp.left)
            make.right.equalTo(self.identityView.snp.right)
            make.height.equalTo(80)
        }
        self.netBtn.snp.makeConstraints { make in
            make.left.equalTo(32)
            make.right.equalTo(-32)
            make.height.equalTo(54)
            make.bottom.equalTo(-UIDevice.xq_safeTop() - 24)
        }
    }
    
    
    private func updateTopInfo() {
        guard let model = dataSource else {return}
        
        self.lineView.isHidden = false
        
        self.identityView.content = model.id_front_msg
        self.faceView.content = model.face_msg
        
        self.identityView.imageName = model.embedded?.measured
        self.faceView.imageName = model.hundreds?.measured
        
        self.identityView.isFinish = model.embedded?.orders == 1
        self.faceView.isFinish = model.hundreds?.orders == 1
    }
    
    
    private func clickIdentity() {
        let vc = XQPublicIdentityAccureController()
        vc.navTitle = self.navTitle
        vc.identityType = dataSource?.embedded?.internalValue ?? ""
        vc.disciplinary = dataSource?.disciplinary
        vc.thousands = dataSource?.thousands
        vc.successHandle = {[weak self] (identityModel,idType,startT) in
            guard let srongify = self else {return}
            srongify.selectName = identityModel.pardons
            srongify.selectNumber = identityModel.parole
            if let yearStr = identityModel.charged,let monthStr = identityModel.capitally,let dayStr = identityModel.kill {
                srongify.selectBirthday = "\(yearStr)/\(monthStr)/\(dayStr)"
            }
            srongify.identityType = idType
            srongify.popShow(model: identityModel,startT: startT)
        }
        self.navigationController?.pushViewController(vc, animated: true)
    }
    
    private func clickFace() {
        
        if (!self.identityView.isFinish) {
            XQHud.showToast(message:"Please upload a photo of your identification document first")
            return
        }
        
        startTime = XQTimeTool.nowTime()
        
        let contentView = XQPublicIdentityFacePopView()
        contentView.frame = CGRect(x: 0, y:( UIDevice.xq_height() - 561) / 2, width: UIDevice.xq_width(), height: 561)
        contentView.sureHandle = {[weak self] in
            guard let srongify = self else {return}
            srongify.openCamera()
            XQHud.hidePop()
        }
        contentView.cancelHandle = {
            XQHud.hidePop()
        }
        XQHud.showPop(contentView)
    }
    
    private func popShow(model : XQOrderPublishIdentityInfoModel,startT : Int64) {
        let contentView = XQPublicIdentityPopAccureView()
        contentView.frame = CGRect(x: 0, y:( UIDevice.xq_height() - 561) / 2, width: UIDevice.xq_width(), height: 561)
        contentView.sureHandle = {[weak self] in
            guard let srongify = self else {return}
            srongify.sureClick(startT: startT)
        }
        contentView.cancelHandle = {
            XQHud.hidePop(controller: self)
        }
        contentView.textFieldChangedHandle = {[weak self] (key,text) in
            guard let srongify = self else {return}
            srongify.popTextFieldChangedHandle(key: key, text: text)
        }
        contentView.clickBirthdayHandle = {[weak self] in
            guard let srongify = self else {return}
            srongify.showBithdayPopView(accureView: contentView,model: model)
           
        }
        XQHud.showPop(contentView,controller: self)
        contentView.model = model
    }
    
    private func showBithdayPopView(accureView : XQPublicIdentityPopAccureView,model : XQOrderPublishIdentityInfoModel) {
        let birthdayPopView = XQPublicIdentityBirthdayPopView()
        birthdayPopView.frame = CGRect(x: 0, y:( UIDevice.xq_height() - 561) / 2, width: UIDevice.xq_width(), height: 561)
        birthdayPopView.setSelectData(date: self.selectBirthday)
        birthdayPopView.sureHandle = {[weak self] (date) in
            guard let srongify = self else {return}
            XQHud.hidePop(controller: srongify)
            srongify.updateSelectBirthday(date: date,accureView: accureView,model: model)
        }
        birthdayPopView.cancelHandle = {
            XQHud.hidePop(controller: self)
        }
        XQHud.showPop(birthdayPopView,controller: self)
    }
    
    private func popTextFieldChangedHandle(key : String,text : String) {
        if (key == "pardons") {
            self.selectName = text
        }else if (key == "parole") {
            self.selectNumber = text
        }
    }
    
    private func updateSelectBirthday(date : String,accureView : XQPublicIdentityPopAccureView,model : XQOrderPublishIdentityInfoModel) {
        
        self.selectBirthday = date
        
        var dm = model
        
        guard let vm = dm.penalty else {return}
        
        for (index,value) in vm.enumerated() {
            if (value.object == "pardons") {
                dm.penalty?[index].prior = self.selectName
            }else if (value.object == "parole") {
                dm.penalty?[index].prior = self.selectNumber
            }else if (value.object == "statistically") {
                dm.penalty?[index].prior = self.selectBirthday
            }
        }

        accureView.model = dm
    }
    
    private func sureClick(startT : Int64) {
        var params : [String : String] = [
            "statistically" : self.selectBirthday ?? "",
            "parole" : self.selectNumber ?? "",
            "pardons" : self.selectName ?? "",
        ]
        
        if (!identityType.isEmpty) {
            params["internal"] = identityType
            params["spectrophotometer"] = "11"
        }else {
            params["spectrophotometer"] = "10"
        }
        
        XQHud.showLoading(controller: self)
        XQNetworkManager.shared.postRequest(url: "/figures/harassment", parameters: params) {[weak self] response, error in
            guard let srongify = self else {return}
            XQHud.hideLoading(controller: srongify)
            
            if (response?.object == 0) {
                XQHud.hidePop(controller: srongify)
                srongify.refreshData()
                
                srongify.notifyIdentifyRisk(numberType: "3", startT: startT)
            }else {
                XQHud.showToast(message: response?.patients ?? "Network Connection Error")
            }
        }
    }
    
    @objc private func nextClick() {
        if !self.identityView.isFinish {
            clickIdentity()
            return
        }
        
        if !self.faceView.isFinish {
            clickFace()
            return
        }
        
        self.navigationController?.popViewController(animated: true)
    }
    
    
    private func openCamera() {
        let authStatus = AVCaptureDevice.authorizationStatus(for: .video)
        AVCaptureDevice.requestAccess(for: .video) { granted in
            DispatchQueue.main.async {
                if granted {
                    if UIImagePickerController.isSourceTypeAvailable(.camera) {
                        let picker = UIImagePickerController()
                        picker.delegate = self
                        picker.sourceType = .camera
                        picker.cameraDevice = .front
                        self.present(picker, animated: true, completion: nil)
                    }
                } else {
                    if authStatus == .denied {
                        self.showAccessDeniedAlert(message: "Please enable access to Camera in Settings.")
                    }
                }
            }
        }
    }
    
    private func showAccessDeniedAlert(message : String) {
        DispatchQueue.main.async {
            XQAlertManager.showDeniedAccessPopAlert(on: self, message:message)
        }
    }
    
    private func uploadPhoto(image : UIImage, isCamera : Bool) {
        let tens = isCamera ? "1" : "2"
        let spectrophotometer = "10"
        guard let imageData : Data = image.toMaxData(maxSizeInKB: 512) else {return}
        
        let params : [String : Any] = [
            "tens" : tens,
            "spectrophotometer" : spectrophotometer,
            "privilegeFaces" : imageData
        ]
        
        XQHud.showLoading(controller: self)
        XQNetworkManager.shared.uploadImage(url: "/figures/firing", parameters: params,imageData: imageData) {[weak self] response, error in
            guard let srongify = self else {return}
            XQHud.hideLoading(controller: srongify)
            if (response?.object == 0) {
                srongify.refreshData()
                srongify.notifyIdentifyRisk(numberType: "4", startT: srongify.startTime)
            }else {
                XQHud.showToast(message: response?.patients ?? "Network Connection Error")
            }
        }
    }
    
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        if let image = info[.originalImage] as? UIImage {
            let isCamera = picker.sourceType == .camera
            // 关闭图片选择器
            picker.dismiss(animated: true) {
                // 上传图片
                self.uploadPhoto(image: image, isCamera: isCamera)
            }
        }
    }
    
    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        dismiss(animated: true)
    }
    
    private func notifyIdentifyRisk(numberType : String,startT : Int64) {
        endTime = XQTimeTool.nowTime()
        XQAnalysisManager.shared.notifyRisk(numberType: numberType, longitude: self.longitude, latitude: self.latitude, startT: startT, endT: endTime, orderId: "")
    }
    
}
